import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/common/ProfileDTO.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerStudent.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/studentSidebar.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as uHtml;
import '../../themes/appTheme.dart';

class StudentProfileSettings extends StatefulWidget {
  static const String routeName = '/student/profile';
  @override
  State<StudentProfileSettings> createState() => _StudentProfileSettingsState();
}

class _StudentProfileSettingsState extends State<StudentProfileSettings> {
  final UserController _usercontroller = Get.find();
  var box = Hive.box('appconfig');

  @override
  void initState() {
    bool isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student;
    if (isStudent) {
      Future.delayed(Duration(milliseconds: 300), () {
        _usercontroller.getProfile();
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentProfileSettings');
    StudentDetailsEditFormModel formModel = StudentDetailsEditFormModel();
    var form = formModel.form;
    var dateformat = new DateFormat('MM/dd/yyyy');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.studentPageItems
        .indexWhere((page) => page.route == Get.currentRoute);

    final PageStyles _pageStyles = PageStyles();

    return Scaffold(
      backgroundColor: Get.isDarkMode ? Colors.black : Colors.transparent,
      resizeToAvoidBottomInset: false,
      appBar: isSmallScreen ? CustomAppBar(title: 'Profile'.tr) : null,
      drawer: isSmallScreen ? StudentAppDrawer() : null,
      body: Container(
        height: double.infinity,
        decoration: _pageStyles.pageBoxDecoration(),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Visibility(
                visible: !isSmallScreen,
                child: StudentSidebarX(
                    selectedIndex: _selectedSidebarItem,
                    isBigScreen: isBigScreen)),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Get.isDarkMode
                      ? AppTheme.colors.darkTheme1
                      : Colors.black.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(6.0),
                ),
                 margin: _pageStyles.mainContainerWithPaginationEdgeInsets(),
                child: Obx(() {
                  if (_usercontroller.profile.value.userId != null) {
                    Settings _classSettings =
                        _usercontroller.profile.value.settings as Settings;
                    form.control('username').value =
                        _usercontroller.profile.value.userName;
                    form.control('security').value =
                        _usercontroller.profile.value.accessCode;
                    form.control('firstname').value =
                        _usercontroller.profile.value.firstName;
                    form.control('lastname').value =
                        _usercontroller.profile.value.lastName;
                    form.control('email').value =
                        _usercontroller.profile.value.email;
                    if (_usercontroller.profile.value.dateOfBirth != null)
                      form.control('dateofbirth').value = dateformat.parse(
                          _usercontroller.profile.value.dateOfBirth.toString());
                    form.control('nickname').value =
                        _usercontroller.profile.value.nickName;
                    form.control('gender').value =
                        _usercontroller.profile.value.gender;
                    form.control('texttype').value =
                        _classSettings.language ?? 'Simplified';
                    form.control('audiotype').value =
                        _classSettings.lang ?? 'Mandarin';
                    form.control('pinyinenabled').value =
                        _classSettings.pinyin ?? true;
                    _usercontroller.setLanguage(_classSettings.language);
                    _usercontroller.setLang(_classSettings.lang);
                    _usercontroller.setPinyin(_classSettings.pinyin);
                    return Container(
                      margin: EdgeInsets.all(12.0),
                      decoration: BoxDecoration(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.white.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(3.0),
                      ),
                      child: SingleChildScrollView(
                        primary: false,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 36.0, vertical: 18.0),
                          child: ReactiveForm(
                            formGroup: form,
                            child: Column(
                              children: <Widget>[
                                ReactiveTextField(
                                  formControlName: 'username',
                                  style: Get.textTheme.bodySmall,
                                  decoration: InputDecoration(
                                    labelText: 'User Name',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  readOnly: true,
                                ),
                                ReactiveTextField(
                                  formControlName: 'security',
                                  style: Get.textTheme.bodySmall,
                                  decoration: InputDecoration(
                                    labelText: 'Security Identifier',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  readOnly: true,
                                ),
                                ReactiveTextField(
                                  formControlName: 'email',
                                  style: Get.textTheme.bodySmall,
                                  decoration: InputDecoration(
                                    labelText: 'Email',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  readOnly: true,
                                ),
                                ReactiveTextField(
                                  formControlName: 'firstname',
                                  style: Get.textTheme.bodySmall,
                                  decoration: InputDecoration(
                                    labelText: 'First Name',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  readOnly: true,
                                ),
                                ReactiveTextField(
                                  formControlName: 'lastname',
                                  style: Get.textTheme.bodySmall,
                                  decoration: InputDecoration(
                                    labelText: 'Last Name',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  readOnly: true,
                                ),
                                SizedBox(height: 24.0),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'gender',
                                  decoration: InputDecoration(
                                    labelText: 'Gender',
                                    labelStyle: Get.textTheme.bodySmall,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  borderColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme7
                                      : Colors.blueGrey,
                                  selectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Get.theme.primaryColor,
                                  unselectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[300],
                                  children: const {
                                    'male': Text('Male',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'female': Text('Female',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),
                                ReactiveTextField<DateTime>(
                                  formControlName: 'dateofbirth',
                                  readOnly: true,
                                  decoration: InputDecoration(
                                    labelText: 'Birthday',
                                    labelStyle: Get.textTheme.bodySmall,
                                    suffixIcon: ReactiveDatePicker<DateTime>(
                                      formControlName: 'dateofbirth',
                                      firstDate: DateTime(1990),
                                      lastDate: DateTime(2030),
                                      builder: (context, picker, child) {
                                        return IconButton(
                                          onPressed: picker.showPicker,
                                          icon: Icon(
                                            Icons.date_range,
                                            color: Get.theme.primaryColorDark,
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                                ReactiveTextField(
                                  formControlName: 'nickname',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'Nick Name',
                                    labelStyle: Get.textTheme.bodySmall,
                                  ),
                                  maxLength: 150,
                                ),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'audiotype',
                                  decoration: InputDecoration(
                                    labelText: 'Audio',
                                    labelStyle: Get.textTheme.bodySmall,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  borderColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme7
                                      : Colors.blueGrey,
                                  selectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Get.theme.primaryColor,
                                  unselectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[300],
                                  children: {
                                    'Mandarin': Text('Mandarin'.tr,
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'Cantonese': Text('Cantonese'.tr,
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'No_audio': Text('No Audio'.tr,
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),
                                ReactiveValueListenableBuilder<String>(
                                  formControlName: 'texttype',
                                  builder: (context, control, child) {
                                    Log.debug(
                                        'texttype listen control.value=${control.value}');
                                    return Visibility(
                                        visible: control.value != 'No text',
                                        child: ReactiveSwitchListTile(
                                          title: Text(
                                            'Pinyin',
                                            style: Get.textTheme.bodySmall,
                                          ),
                                          subtitle: Padding(
                                            padding: const EdgeInsets.symmetric(
                                                vertical: 9.0),
                                            child: Text(
                                              'When text option set to NO TEXT, pinyin can not be displayed.',
                                              style: Theme.of(context)
                                                  .textTheme
                                                  .labelSmall
                                                  ?.copyWith(fontSize: 12.0),
                                            ),
                                          ),
                                          formControlName: 'pinyinenabled',
                                        ));
                                  },
                                ),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'texttype',
                                  decoration: InputDecoration(
                                    labelText: 'Text',
                                    labelStyle: Get.textTheme.bodySmall,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  borderColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme7
                                      : Colors.blueGrey,
                                  selectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Get.theme.primaryColor,
                                  unselectedColor: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[300],
                                  children: const {
                                    'Simplified': Text('Simplified',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'Traditional': Text('Traditional',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'No text': Text('No Text',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 14.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    ReactiveFormConsumer(
                                      builder: (context, form, child) {
                                        ProfileDTO dto = new ProfileDTO();
                                        dto.email = form.control('email').value;

                                        if (form.control('dateofbirth').value !=
                                            null)
                                          dto.birthday = dateformat.format(form
                                              .control('dateofbirth')
                                              .value);
                                        dto.firstName =
                                            form.control('firstname').value;
                                        dto.lastName =
                                            form.control('lastname').value;
                                        dto.gender =
                                            form.control('gender').value;
                                        dto.nickName =
                                            form.control('nickname').value;
                                        dto.settings = new Settings();
                                        dto.settings?.pinyin =
                                            form.control('pinyinenabled').value;
                                        dto.settings?.lang =
                                            form.control('audiotype').value;
                                        dto.settings?.language =
                                            form.control('texttype').value;

                                        if (dto.settings?.language ==
                                            'No text') {
                                          dto.settings?.pinyin = false;
                                        }

                                        return ElevatedButton(
                                            style: ButtonStyle(
                                                backgroundColor:
                                                    MaterialStateProperty.all(
                                              Get.theme.primaryColorDark,
                                            )),
                                            child: Text(
                                              'Submit'.tr,
                                              style: TextStyle(
                                                fontSize: 16.0,
                                                color: Get.isDarkMode
                                                    ? Colors.black
                                                    : Get.theme
                                                        .primaryColorLight,
                                                letterSpacing: 1.0,
                                              ),
                                            ),
                                            onPressed: () {
                                              if (form.valid) {

                                                _usercontroller.setLanguage(
                                                    dto.settings?.language);
                                                _usercontroller.setLang(
                                                    dto.settings?.lang);
                                                _usercontroller.setPinyin(
                                                    dto.settings?.pinyin);

                                                if (GetPlatform.isWeb) {
                                                  uHtml.window.localStorage[
                                                          'lang'] =
                                                      '${dto.settings?.lang ?? 'Mandarin'}';
                                                  uHtml.window.localStorage[
                                                          'language'] =
                                                      '${dto.settings?.language ?? 'Simplified'}';
                                                }
                                                if (dto.settings != null) {
                                                  _usercontroller
                                                      .setCurrentProfileSettings(
                                                          dto.settings);
                                                }
                                                 _usercontroller
                                                .updateProfile(dto)
                                                .then((statusResult) {
                                              if (statusResult.status == 1000) {
                                                showSnackMsg(
                                                    'Successfully updated');
                                              } else {
                                                showSnackMsg('Error to update');
                                              }
                                            });
                                              }
                                            });
                                      },
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  } else {
                    return Text('');
                  }
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
